package cn.javablog.shiro;

import cn.hutool.json.JSONUtil;
import cn.javablog.common.exception.DIVException;
import cn.javablog.common.lang.Result;
import cn.javablog.entity.TUser;
import cn.javablog.service.TUserService;
import cn.javablog.util.JwtUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    TUserService tUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        String id = jwtUtils.getClaimByToken((String)jwtToken.getPrincipal()).getSubject();
        TUser tuser = tUserService.getById(Integer.valueOf(id));
        if(tuser==null){
            throw new UnknownAccountException("账户不存在");
        }
        if(tuser.getType()==-1){
            throw new LockedAccountException("账户已被锁定");
        }
        AccountProfile profile = new AccountProfile();
        BeanUtils.copyProperties(tuser,profile);
//        System.out.println("tokey"+jwtToken);
        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }
}
